<?php

namespace App\Console\Commands;

use App\Models\Permission;
use Illuminate\Console\Command;

class CreatePermission extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'permission:create 
                            {name : Name of permission}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Creating role\'s permission';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $validator = \Validator::make([
            'permission_name' => $this->argument('name'),
        ], [
            'permission_name' => [
                'required',
                'max:50',
                'string',
                'unique:permissions',
            ],
        ]);

        if ($validator->fails()) {
            $this->info('Permission not created. See errors below:');

            foreach ($validator->errors()->all() as $error) {
                $this->error($error);
            }

            return 1;
        }

        $permission = Permission::create($validator->validated());
        $this->info(\sprintf('Permission %s was created.', $permission->permission_name));

        return 0;
    }
}
